//////////////////////////////////////////////////////////////////////////////////////////////
//	File			:	"BitmapFont.cpp"
//
//	Author			:	Mike Davis, Matt Stover, James Thornton, Keith Webster
//	
//	Project			:	TacWars
//
//	Last Modified	:	11/6/2013
//
//	Purpose			:	
//
//////////////////////////////////////////////////////////////////////////////////////////////
#include "BitmapFont.h"

#include "../SGD Wrappers/CSGD_TextureManager.h"
#include "../SGD Wrappers/SGD_String.h"
#include <cassert>
#include <fstream>

using namespace std;

BitmapFont::BitmapFont	(TCHAR* _fontName)

{
	imageID		= -1;
	fontName = _fontName;
}
BitmapFont::~BitmapFont(void)
{
}
void BitmapFont::Initialize( void )
{
	TOSTRINGSTREAM toss;
	toss << _T("resource/Fonts/") << fontName << _T(".png");
	imageID		= CSGD_TextureManager::GetInstance()->LoadTexture(toss.str().c_str());

	toss.str(_T(""));
	toss << _T("resource/Fonts/") << fontName << _T(".fnt");
	
	ifstream stream(toss.str().c_str());

	stream >> fontHeight >> spacePix >> tabSpace;

	while(!stream.eof())
	{
		char c;
		stream >> c;
		int x, y, wid, adv;
		stream >> x >> y >> wid >> adv;
		Chars[(int)c].x = x;
		Chars[(int)c].y = y;
		Chars[(int)c].width = wid;
		Chars[(int)c].advance = adv;
	}
}
void BitmapFont::Shutdown( void )
{
	CSGD_TextureManager::GetInstance()->UnloadTexture( imageID );
	imageID = -1;
}
void BitmapFont::Draw( const TCHAR* strOutput, int nX, int nY,
						float fScale, DWORD dwColor ) const
{
	assert( imageID != -1 && "BitmapFont::Draw - image is not set" );

	int colStart = nX;
	int printed = 0;

	// Loop through each character in the string
	for( int i = 0; strOutput[ i ]; i++ )
	{
		// Get the character out of the string
		TCHAR ch = strOutput[ i ];
		


		if( ch == _T(' ') )
		{
			nX += (int)(spacePix * fScale);
			continue;
		}
		else if( ch == _T('\n') )
		{
			nY += (int)(fontHeight * fScale);
			nX =  colStart;
			continue;
		}
		else if( ch == _T('\t') )
		{
			int tab  = 5 - (printed % 5);

			nX += (int)(tab *spacePix * fScale);
			continue;
		}


		RECT rCell;
		rCell.left = Chars[(int)ch].x;
		rCell.top = Chars[(int)ch].y;
		rCell.right = Chars[(int)ch].x + Chars[(int)ch].width;
		rCell.bottom = Chars[(int)ch].y + fontHeight;

		CSGD_TextureManager::GetInstance()->Draw(
			imageID, nX, nY, 
			fScale, fScale, &rCell,
			0.0f, 0.0f, 0.0f, dwColor );

		nX += (int)(Chars[(int)ch].advance * fScale);
		printed++;
	}
}

